
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>31.4. runpy — Locating and executing Python modules &#8212; Python 3.6.3 documentation</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.6.3',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true,
        SOURCELINK_SUFFIX: '.txt'
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.6.3 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="31.5. importlib — The implementation of import" href="importlib.html" />
    <link rel="prev" title="31.3. modulefinder — Find modules used by a script" href="modulefinder.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/library/runpy.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    <script type="text/javascript" src="../_static/switchers.js"></script>
    
    
 

  </head>
  <body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="importlib.html" title="31.5. importlib — The implementation of import"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="modulefinder.html" title="31.3. modulefinder — Find modules used by a script"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <span class="language_switcher_placeholder">en</span>
          <span class="version_switcher_placeholder">3.6.3</span>
          <a href="../index.html">Documentation </a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" accesskey="U">31. Importing Modules</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-runpy">
<span id="runpy-locating-and-executing-python-modules"></span><h1>31.4. <a class="reference internal" href="#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal"><span class="pre">runpy</span></code></a> — Locating and executing Python modules<a class="headerlink" href="#module-runpy" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.6/Lib/runpy.py">Lib/runpy.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal"><span class="pre">runpy</span></code></a> module is used to locate and run Python modules without
importing them first. Its main use is to implement the <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal"><span class="pre">-m</span></code></a> command
line switch that allows scripts to be located using the Python module
namespace rather than the filesystem.</p>
<p>Note that this is <em>not</em> a sandbox module - all code is executed in the
current process, and any side effects (such as cached imports of other
modules) will remain in place after the functions have returned.</p>
<p>Furthermore, any functions and classes defined by the executed code are not
guaranteed to work correctly after a <a class="reference internal" href="#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal"><span class="pre">runpy</span></code></a> function has returned.
If that limitation is not acceptable for a given use case, <a class="reference internal" href="importlib.html#module-importlib" title="importlib: The implementation of the import machinery."><code class="xref py py-mod docutils literal"><span class="pre">importlib</span></code></a>
is likely to be a more suitable choice than this module.</p>
<p>The <a class="reference internal" href="#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal"><span class="pre">runpy</span></code></a> module provides two functions:</p>
<dl class="function">
<dt id="runpy.run_module">
<code class="descclassname">runpy.</code><code class="descname">run_module</code><span class="sig-paren">(</span><em>mod_name</em>, <em>init_globals=None</em>, <em>run_name=None</em>, <em>alter_sys=False</em><span class="sig-paren">)</span><a class="headerlink" href="#runpy.run_module" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">Execute the code of the specified module and return the resulting module
globals dictionary. The module’s code is first located using the standard
import mechanism (refer to <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> for details) and then executed in a
fresh module namespace.</p>
<p>The <em>mod_name</em> argument should be an absolute module name.
If the module name refers to a package rather than a normal
module, then that package is imported and the <code class="docutils literal"><span class="pre">__main__</span></code> submodule within
that package is then executed and the resulting module globals dictionary
returned.</p>
<p>The optional dictionary argument <em>init_globals</em> may be used to pre-populate
the module’s globals dictionary before the code is executed. The supplied
dictionary will not be modified. If any of the special global variables
below are defined in the supplied dictionary, those definitions are
overridden by <a class="reference internal" href="#runpy.run_module" title="runpy.run_module"><code class="xref py py-func docutils literal"><span class="pre">run_module()</span></code></a>.</p>
<p>The special global variables <code class="docutils literal"><span class="pre">__name__</span></code>, <code class="docutils literal"><span class="pre">__spec__</span></code>, <code class="docutils literal"><span class="pre">__file__</span></code>,
<code class="docutils literal"><span class="pre">__cached__</span></code>, <code class="docutils literal"><span class="pre">__loader__</span></code> and <code class="docutils literal"><span class="pre">__package__</span></code> are set in the globals
dictionary before the module code is executed (Note that this is a
minimal set of variables - other variables may be set implicitly as an
interpreter implementation detail).</p>
<p><code class="docutils literal"><span class="pre">__name__</span></code> is set to <em>run_name</em> if this optional argument is not
<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal"><span class="pre">None</span></code></a>, to <code class="docutils literal"><span class="pre">mod_name</span> <span class="pre">+</span> <span class="pre">'.__main__'</span></code> if the named module is a
package and to the <em>mod_name</em> argument otherwise.</p>
<p><code class="docutils literal"><span class="pre">__spec__</span></code> will be set appropriately for the <em>actually</em> imported
module (that is, <code class="docutils literal"><span class="pre">__spec__.name</span></code> will always be <em>mod_name</em> or
<code class="docutils literal"><span class="pre">mod_name</span> <span class="pre">+</span> <span class="pre">'.__main__</span></code>, never <em>run_name</em>).</p>
<p><code class="docutils literal"><span class="pre">__file__</span></code>, <code class="docutils literal"><span class="pre">__cached__</span></code>, <code class="docutils literal"><span class="pre">__loader__</span></code> and <code class="docutils literal"><span class="pre">__package__</span></code> are
<a class="reference internal" href="../reference/import.html#import-mod-attrs"><span class="std std-ref">set as normal</span></a> based on the module spec.</p>
<p>If the argument <em>alter_sys</em> is supplied and evaluates to <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal"><span class="pre">True</span></code></a>,
then <code class="docutils literal"><span class="pre">sys.argv[0]</span></code> is updated with the value of <code class="docutils literal"><span class="pre">__file__</span></code> and
<code class="docutils literal"><span class="pre">sys.modules[__name__]</span></code> is updated with a temporary module object for the
module being executed. Both <code class="docutils literal"><span class="pre">sys.argv[0]</span></code> and <code class="docutils literal"><span class="pre">sys.modules[__name__]</span></code>
are restored to their original values before the function returns.</p>
<p>Note that this manipulation of <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal"><span class="pre">sys</span></code></a> is not thread-safe. Other threads
may see the partially initialised module, as well as the altered list of
arguments. It is recommended that the <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal"><span class="pre">sys</span></code></a> module be left alone when
invoking this function from threaded code.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal"><span class="pre">-m</span></code></a> option offering equivalent functionality from the
command line.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.1: </span>Added ability to execute packages by looking for a <code class="docutils literal"><span class="pre">__main__</span></code> submodule.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.2: </span>Added <code class="docutils literal"><span class="pre">__cached__</span></code> global variable (see <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3147"><strong>PEP 3147</strong></a>).</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.4: </span>Updated to take advantage of the module spec feature added by
<span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0451"><strong>PEP 451</strong></a>. This allows <code class="docutils literal"><span class="pre">__cached__</span></code> to be set correctly for modules
run this way, as well as ensuring the real module name is always
accessible as <code class="docutils literal"><span class="pre">__spec__.name</span></code>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="runpy.run_path">
<code class="descclassname">runpy.</code><code class="descname">run_path</code><span class="sig-paren">(</span><em>file_path</em>, <em>init_globals=None</em>, <em>run_name=None</em><span class="sig-paren">)</span><a class="headerlink" href="#runpy.run_path" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-4">Execute the code at the named filesystem location and return the resulting
module globals dictionary. As with a script name supplied to the CPython
command line, the supplied path may refer to a Python source file, a
compiled bytecode file or a valid sys.path entry containing a <code class="docutils literal"><span class="pre">__main__</span></code>
module (e.g. a zipfile containing a top-level <code class="docutils literal"><span class="pre">__main__.py</span></code> file).</p>
<p>For a simple script, the specified code is simply executed in a fresh
module namespace. For a valid sys.path entry (typically a zipfile or
directory), the entry is first added to the beginning of <code class="docutils literal"><span class="pre">sys.path</span></code>. The
function then looks for and executes a <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal"><span class="pre">__main__</span></code></a> module using the
updated path. Note that there is no special protection against invoking
an existing <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal"><span class="pre">__main__</span></code></a> entry located elsewhere on <code class="docutils literal"><span class="pre">sys.path</span></code> if
there is no such module at the specified location.</p>
<p>The optional dictionary argument <em>init_globals</em> may be used to pre-populate
the module’s globals dictionary before the code is executed. The supplied
dictionary will not be modified. If any of the special global variables
below are defined in the supplied dictionary, those definitions are
overridden by <a class="reference internal" href="#runpy.run_path" title="runpy.run_path"><code class="xref py py-func docutils literal"><span class="pre">run_path()</span></code></a>.</p>
<p>The special global variables <code class="docutils literal"><span class="pre">__name__</span></code>, <code class="docutils literal"><span class="pre">__spec__</span></code>, <code class="docutils literal"><span class="pre">__file__</span></code>,
<code class="docutils literal"><span class="pre">__cached__</span></code>, <code class="docutils literal"><span class="pre">__loader__</span></code> and <code class="docutils literal"><span class="pre">__package__</span></code> are set in the globals
dictionary before the module code is executed (Note that this is a
minimal set of variables - other variables may be set implicitly as an
interpreter implementation detail).</p>
<p><code class="docutils literal"><span class="pre">__name__</span></code> is set to <em>run_name</em> if this optional argument is not
<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal"><span class="pre">None</span></code></a> and to <code class="docutils literal"><span class="pre">'&lt;run_path&gt;'</span></code> otherwise.</p>
<p>If the supplied path directly references a script file (whether as source
or as precompiled byte code), then <code class="docutils literal"><span class="pre">__file__</span></code> will be set to the
supplied path, and <code class="docutils literal"><span class="pre">__spec__</span></code>, <code class="docutils literal"><span class="pre">__cached__</span></code>, <code class="docutils literal"><span class="pre">__loader__</span></code> and
<code class="docutils literal"><span class="pre">__package__</span></code> will all be set to <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal"><span class="pre">None</span></code></a>.</p>
<p>If the supplied path is a reference to a valid sys.path entry, then
<code class="docutils literal"><span class="pre">__spec__</span></code> will be set appropriately for the imported <code class="docutils literal"><span class="pre">__main__</span></code>
module (that is, <code class="docutils literal"><span class="pre">__spec__.name</span></code> will always be <code class="docutils literal"><span class="pre">__main__</span></code>).
<code class="docutils literal"><span class="pre">__file__</span></code>, <code class="docutils literal"><span class="pre">__cached__</span></code>, <code class="docutils literal"><span class="pre">__loader__</span></code> and <code class="docutils literal"><span class="pre">__package__</span></code> will be
<a class="reference internal" href="../reference/import.html#import-mod-attrs"><span class="std std-ref">set as normal</span></a> based on the module spec.</p>
<p>A number of alterations are also made to the <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal"><span class="pre">sys</span></code></a> module. Firstly,
<code class="docutils literal"><span class="pre">sys.path</span></code> may be altered as described above. <code class="docutils literal"><span class="pre">sys.argv[0]</span></code> is updated
with the value of <code class="docutils literal"><span class="pre">file_path</span></code> and <code class="docutils literal"><span class="pre">sys.modules[__name__]</span></code> is updated
with a temporary module object for the module being executed. All
modifications to items in <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal"><span class="pre">sys</span></code></a> are reverted before the function
returns.</p>
<p>Note that, unlike <a class="reference internal" href="#runpy.run_module" title="runpy.run_module"><code class="xref py py-func docutils literal"><span class="pre">run_module()</span></code></a>, the alterations made to <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal"><span class="pre">sys</span></code></a>
are not optional in this function as these adjustments are essential to
allowing the execution of sys.path entries. As the thread-safety
limitations still apply, use of this function in threaded code should be
either serialised with the import lock or delegated to a separate process.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="../using/cmdline.html#using-on-interface-options"><span class="std std-ref">Interface options</span></a> for equivalent functionality on the
command line (<code class="docutils literal"><span class="pre">python</span> <span class="pre">path/to/script</span></code>).</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.4: </span>Updated to take advantage of the module spec feature added by
<span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0451"><strong>PEP 451</strong></a>. This allows <code class="docutils literal"><span class="pre">__cached__</span></code> to be set correctly in the
case where <code class="docutils literal"><span class="pre">__main__</span></code> is imported from a valid sys.path entry rather
than being executed directly.</p>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt><span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0338"><strong>PEP 338</strong></a> – Executing modules as scripts</dt>
<dd>PEP written and implemented by Nick Coghlan.</dd>
<dt><span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0366"><strong>PEP 366</strong></a> – Main module explicit relative imports</dt>
<dd>PEP written and implemented by Nick Coghlan.</dd>
<dt><span class="target" id="index-8"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0451"><strong>PEP 451</strong></a> – A ModuleSpec Type for the Import System</dt>
<dd>PEP written and implemented by Eric Snow</dd>
</dl>
<p><a class="reference internal" href="../using/cmdline.html#using-on-general"><span class="std std-ref">Command line and environment</span></a> - CPython command line details</p>
<p class="last">The <a class="reference internal" href="importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal"><span class="pre">importlib.import_module()</span></code></a> function</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="modulefinder.html"
                        title="previous chapter">31.3. <code class="docutils literal"><span class="pre">modulefinder</span></code> — Find modules used by a script</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="importlib.html"
                        title="next chapter">31.5. <code class="docutils literal"><span class="pre">importlib</span></code> — The implementation of <code class="docutils literal"><span class="pre">import</span></code></a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">Report a Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.6/Doc/library/runpy.rst"
            rel="nofollow">Show Source
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="importlib.html" title="31.5. importlib — The implementation of import"
             >next</a> |</li>
        <li class="right" >
          <a href="modulefinder.html" title="31.3. modulefinder — Find modules used by a script"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <span class="language_switcher_placeholder">en</span>
          <span class="version_switcher_placeholder">3.6.3</span>
          <a href="../index.html">Documentation </a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" >31. Importing Modules</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 2001-2017, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Oct 14, 2017.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.6.4.
    </div>

  </body>
</html>